package controler;

import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import dao.UsuarioDAO;

@ManagedBean
@SessionScoped
public class ControlerUS implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2123785959575842458L;

	public ControlerUS() {
		// TODO Auto-generated constructor stub
	}
	
	private UsuarioDAO usuarioDAO = new UsuarioDAO();
	
	public void gerarRelatorioUS(ActionEvent action)  
            throws ParseException {  		
		FacesContext context = FacesContext.getCurrentInstance();
		List lista = usuarioDAO.listaUSALL();		
		//new GerarRelatorio().relatorioUSALL(listaUs);
		try {
			
			HttpServletResponse response = (HttpServletResponse) context
					.getExternalContext().getResponse();
			ServletOutputStream responseStream = response.getOutputStream();
			// caminho do jrxml
			InputStream pathjrxml = getClass().getResourceAsStream(
					"../jrxml/reportblog.jasper");
			
			response.setContentType("application/pdf");
			// Seta o nome do arquivo e a disposição: "inline" abre no próprio navegador  
			// Mude para "attachment" para indicar que deve ser feito um download 
			response.setHeader("Content-Disposition",
					"inline; filename=\"relatoriotodosusuarios.pdf\"");
			//JasperReport pathReport = JasperCompileManager
			//		.compileReport(pathjrxml);
			//JasperPrint print = JasperFillManager.fillReport(pathReport, null,
			//		new JRBeanCollectionDataSource(lista));
			
			//JasperExportManager.exportReportToPdfStream(print, responseStream);
			JasperRunManager.runReportToPdfStream(pathjrxml,  
					responseStream, null,new JRBeanCollectionDataSource(lista)); 
			
			responseStream.flush();
			responseStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		finally { 
			context.renderResponse();
            context.responseComplete();  
        } 

	}
	}//fim da classe		

